
import {  compareTwoVdom } from './react-dom';

class Updater {
    constructor(classInstance){
        this.classInstance = classInstance //也就是类的实例
        this.pendingStates = [];//等待更新队列
    }
    addState(partialState){
        this.pendingStates.push(partialState)
        this.emitUpdate(); //触发更新
    }
    emitUpdate(){
        this.updateComponent();//更新组件
    }
    updateComponent(){
        let { classInstance,pendingStates} = this
        if(pendingStates.length>0){
            shouldUpdate(classInstance,this.getState())
        }
    }
    // 基于老状态和pendingState获取新状态
    getState(){
        let { classInstance,pendingStates} = this
        let {state} = classInstance //老状态
        // 更新状态
        pendingStates.forEach((nextState)=>{
            if(typeof nextState === 'function'){
                nextState = nextState(state)
            }
            state = {...state,...nextState}
        })
        pendingStates.length = 0 //清空数组
        return state
    }
}
function shouldUpdate(classInstance,nextState){
    classInstance.state = nextState
    classInstance.forceUpdate() //让类的实例强行更新
}

class Component {
    static isReactComponent = true
    constructor(props){
        this.props = props
        this.state = {}
        this.updater = new Updater(this)
    }
    setState(partialState){
        this.updater.addState(partialState)
    }
    forceUpdate(){
        let oldRenderVdom = this.oldRenderVdom;//之前在mountClassComponent方法中进行过挂载
        let oldDom = oldRenderVdom.dom
        let newRenderVdom = this.render(); //重新render()获取新的vdom，使用新的vdom生成新的真实dom，用新的真实dom替换掉老的dom
        compareTwoVdom(oldDom.parentNode, oldRenderVdom, newRenderVdom);
        this.oldRenderVdom = newRenderVdom; //将新的渲染虚拟dom赋值给this.oldRenderVdom 
    }
}
export default Component